package com.bdmc.smokesensor.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.bdmc.smokesensor.Utils.*;
import com.bdmc.smokesensor.entity.*;
import com.bdmc.smokesensor.services.Rbac_ActionService;
import com.bdmc.smokesensor.services.Rbac_FunctionService;
import com.bdmc.smokesensor.services.Rbac_RoleService;
import com.bdmc.smokesensor.services.Sys_UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
public class Sys_UserController extends BaseController{
    @Autowired
    private Sys_UserService _userSvs;
    @Autowired
    private Rbac_ActionService _actionSvs;
    @Autowired
    private Rbac_FunctionService _funSvs;
    @Autowired
    private Rbac_RoleService _roleSvs;
    

    /**
     * 数据新增或更新，save方法可以执行添加也可以执行更新，如果需要执行持久化的实体存在主键值则更新数据，如果不存在则添加数据。
     */
    @RequestMapping(value = "/save")
    public Msg save(@RequestBody Sys_User user) {
        String action = user.getId()>0?"修改:":"新增:";
        if(user.getId()<=0)
            user.setPassword(CommonUtil.MD5(user.getPassword()));
        try {
            Sys_User u = _userSvs.save(user);
            if(u!=null&&u.getId()>0){
                Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "用户管理", action+u.getLoginName());
                _logSvs.save(log);
                return ResultUtil.success();
            }else
            {
                return ResultUtil.error(-1,"操作失败，请联系管理员。");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage());
            return ResultUtil.error(-1, "数据库已存在该用户名。");
        }

    }

    /** * 查询用户信息 * */
    @RequestMapping(value = "/list")
    public Msg list(@RequestBody Map<String, Object> map) {
        int page = Integer.valueOf(map.get("page").toString()) ;
        String name = map.get("uName").toString();
        int rows = Integer.valueOf(map.get("rows").toString());
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        return ResultUtil.success(_userSvs.findBySqlPageable(dep_id,name,page, rows));
    }

    /** * 用户登陆 * */
    @RequestMapping(value = "/login")
    public Msg login(@RequestBody Map<String, String> map) {
        String loginName = map.get("loginName");
        String password = map.get("password");
        if (loginName == null || password == null || loginName == "" || password == "")
            return ResultUtil.error(-1, "用户名或密码不能为空。");
        password = CommonUtil.MD5(password);
        Sys_User u = _userSvs.findByLoginNameAndPassword(loginName, password);
        if (u != null) {
            Rbac_Role role = _roleSvs.findOneById(u.getRbac_RoleId());
            
            List<Rbac_Action> as = _actionSvs.getRoleActions(role.getStrAction());
            List<Rbac_Function> fs = _funSvs.getFunctionByString(role.getStrFuction());
            //查找按钮权限
            for (Rbac_Function f : fs) {
                List<String> actionList = as.stream().filter(x -> x.getRbacFunctionId() == f.getId())
                        .map(x -> x.getActionCode()).collect(Collectors.toList());
                f.setActions(actionList);
            }
            Map<String, Object> respMap = new HashMap<String, Object>();
            respMap.put("userId", u.getId());
            respMap.put("nickName", u.getNickname());
            respMap.put("loginName", u.getLoginName());
            respMap.put("mobile", u.getMobile());
            respMap.put("joinDate", u.getJoinDate());
            respMap.put("menuList", fs);
            // r
            String token = WebTokenUtil.createJWT(u.getId(), u.getLoginName(),u.getDepartmentId(),u.getLoginName(), 36000000);
            respMap.put("token", token);
            Sys_Log log = new Sys_Log(loginName, getLocalIp() , "用户管理", "登录："+loginName);
            _logSvs.save(log);
            return ResultUtil.success(respMap);
        } else {
            return ResultUtil.error(-1, "用户名或密码错误。");
        }

    }

    /** * 查询用户信息 ,该方法用于测试！！！！！！* */
    @RequestMapping(value = "/find")
    public Sys_User find(Sys_User user) {
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name", match -> match.startsWith())// 模糊查询匹配开头，即{username}%
                .withMatcher("address", match -> match.contains())// 全部模糊查询，即%{address}%
                .withIgnorePaths("password");// 忽略字段，即不管password是什么值都不加入查询条件
        Example<Sys_User> example = Example.of(user, matcher);
        // int i = 3/0;

        return _userSvs.findOne(example);
    }

    /**
     * 删除用户信息，删除信息后返回剩余信息
     */
    @RequestMapping(value = "/delete")
    public Msg delete(@RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        _userSvs.deleteById(id);
        Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "用户管理", "删除："+id);
        _logSvs.save(log);
        return ResultUtil.success();
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/reset_pwd")
    public Msg resetPassword(@RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        Sys_User u = _userSvs.findOneById(id);
        if (u != null) {
            u.setPassword(CommonUtil.MD5("123456"));
            _userSvs.save(u);
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "用户管理", "重置密码"+u.getLoginName());
            _logSvs.save(log);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "用户不存在。");
        }
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/modify_pwd")
    public Msg modifyPassword(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(request.getAttribute("user_id").toString());
        String oldpwd = map.get("oldpwd").toString();
        String newpwd = map.get("newpwd").toString();
        if(newpwd.length()<6){
            return ResultUtil.error(-1, "密码至少要6位数。");
        }
        Sys_User u = _userSvs.findOneById(id);
        if (u != null&&u.getPassword().toLowerCase().equals(CommonUtil.MD5(oldpwd).toLowerCase())) {
            u.setPassword(CommonUtil.MD5(newpwd));
            _userSvs.save(u);
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "用户管理", "修改密码"+u.getLoginName());
            _logSvs.save(log);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "用户不存在或原密码错误。");
        }
    }
}
